import intro from './intro.js';
const DATA_URL = 'http://localhost:8080/output';
async function ProcessFile() {
	const file = document.getElementById('file').files[0];
	await predict(file);
}

let model;
let classes;
async function contentLoaded() {
	model = await tf.loadLayersModel(DATA_URL + '/model.json');
	// model.summary();
	classes = await fetch(DATA_URL + '/classes.json').then(res => res.json());
	document.getElementById('file').addEventListener('change', ProcessFile, false);
}

window.addEventListener("DOMContentLoaded", contentLoaded, false);

async function predict(file) {
	// console.log(file);
	const img = await file2img(file);
	// console.log(img);
	// this.setState({ imgSrc: img.src });
	setTimeout(function () {
		const pred = tf.tidy(function () {
			const x = img2x(img);
			// console.log(x);
			return model.predict(x);
		});
		const results = pred.arraySync()[0].map((score, i) => ({ score, label: classes[i] })).sort((a, b) => b.score - a.score);
		// return results;
		console.log(results);
		
		// this.setState({ results });
	}, 0);
}

async function file2img(f) {
	return new Promise(resolve => {
		const reader = new FileReader();
		reader.readAsDataURL(f);
		reader.onload = (e) => {
			const txt = e.target.result;
			
			// img1尺寸以拉伸，给机器识别，不会真正显示在屏幕上
			const img1 = document.createElement("img");
			img1.src = txt;//将图片base64字符串赋值给img的src
			img1.width = 224;
			img1.height = 224;//这两行必须写，与img2x中的224对应
			img1.onload = () => resolve(img1);
			
			// console.log(txt);
			const result = document.getElementById("result");
			if (result.hasChildNodes()) {
				result.removeChild(result.childNodes[0]);
			}
			
			// img2是真正给用户显示的图片
			const img2 = document.createElement("img");
			img2.src = txt;
			result.appendChild(img2);
		}
	})
}

function img2x(imgEl) {
	return tf.tidy(function (){
		return tf.browser.fromPixels(imgEl).toFloat().sub(255 / 2).div(255 / 2).reshape([1, 224, 224, 3]);
	})
}
